import axios from 'axios';
import router from '@/router';
import config from '@/config';


//
const REQ_INSTANCE = axios.create({
  timeout: 50000,
  headers: {
    'Content-Type': 'application/json'
  },
  data: {}
});

//
REQ_INSTANCE.interceptors.request.use(
  (reqConfig) => {
    reqConfig.url = API_HOST + reqConfig.url;
    let token = window.localStorage.getItem('token');
    if (token) {
      reqConfig.headers['x-access-token'] = token;
    }
    return reqConfig;
  },
  (error) => {
    Promise.reject(error);
  }
);

//
const errorHandler = {};
const handleReponse = (res) => {
  return new Promise((s, f) => {
    res.then(
      (r) => {
        r = r.data;
      },
      (r) => {}
    );
  });
};

const Api = {
  //
  addErrorHandler: (result, cb) => {
    errorHandler[result] = cb;
  },

  //
  page: (url, request) => {
    return handleReponse(REQ_INSTANCE.post(url, request));
  },

  //
  post: (url, request) => {
    return handleReponse(REQ_INSTANCE.post(url, request));
  },

  //
  get: (url, request) => {
    return handleReponse(
      REQ_INSTANCE.get(url, {
        params: request || {}
      })
    );
  },

  //
  download: (url, request) => {
    let query = url;
    if (request) {

      for (let k in request) {
        if (query.indexOf('?') == -1) {
          query += `?${k}=${encodeURIComponent(request[k])}`;
        } else {
          query += `&${k}=${encodeURIComponent(request[k])}`;
        }

      }
    }
    window.open(API_HOST + query);
  },

  //
  upload: (url, file) => {
    let fd = new FormData();
    fd.append('file', file);
    return handleReponse(
      REQ_INSTANCE.post(url, request, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
    ).then((r) => {
      Message.success({
        message: '上传成功'
      });
      return r;
    });
  }

  //mark
};

export default Api;